package com.wva.video.xxljob;

import cn.hutool.core.collection.CollectionUtil;
import com.wva.video.enums.RedisKey;
import com.wva.video.service.VideoUploadService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 清除上传视频过程中一些过期的分片文件和redis键，需扫描redis，建议服务器空闲时期执行
 * @Author: hong
 * @Date: 2025/2/13 18:33:14
 */
@Component
@Slf4j
public class RemoveTimeoutVideoChunks {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    VideoUploadService videoUploadService;

    @XxlJob("removeTimeoutVideoChunks")
    void removeTimeoutVideoChunks() {
        log.info("removeTimeoutVideoChunks定时任务执行");

        //获取过期的文件
        String key = RedisKey.CHUNKS_DEADLINE.format();
        Set<String> members = stringRedisTemplate.opsForZSet().rangeByScore(key, 0, System.currentTimeMillis());
        if (CollectionUtil.isEmpty(members)) {
            log.debug("没有文件");
            XxlJobHelper.log("没有过期的待上传文件需要清理");
            return;
        }

        //遍历集合删除minio里的分片文件
        for (String member : members) {
            //删除minio文件
            XxlJobHelper.log("开始处理过期待删除文件：{}", member);
            try {
                //删除视频分块
                videoUploadService.removeVideoPartsByMd5(member);
                XxlJobHelper.log("删除分块文件成功");
            } catch (Exception e) {
                log.debug("删除文件失败");
                XxlJobHelper.log("删除分块文件失败, e:{}", e);
            }
        }
    }
}
